package com.aiyige.utils;

import android.text.Html;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;

import com.aiyige.R;


import org.apache.commons.text.StringEscapeUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HighLightWordUtil {

    /**
     * 高亮替换
     *
     * @param keyWord 关键词
     * @param title   需替换的标题
     * @return 返回结果字符串
     */
    public static String highLight(String title, String keyWord) {
        if (TextUtils.isEmpty(title)) {
            return "";
        }
        if (TextUtils.isEmpty(keyWord)) {
            return title;
        }
        return highlightSearchKey(title, keyWord);
    }

    private static String highlightSearchKey(String title, String keyword) {
        Spannable highlight;
        Pattern pattern;
        Matcher matcher;

        highlight = (Spannable) Html.fromHtml(StringEscapeUtils.escapeHtml4(title));
        pattern = Pattern.compile("(?i)" + keyword);
        matcher = pattern.matcher(title);
        while (matcher.find()) {
            highlight.setSpan(
                    new ForegroundColorSpan(ColorUtil.getColor(R.color.zwcolor_pink_f93684)),
                    matcher.start(),
                    matcher.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return Html.toHtml(highlight);
    }
}
